﻿///***************************************************************
/// 시  스  템 : Updms.Com
/// 단위시스템 : COM
/// 계      층 : Presentation Layer
/// 프로그램명 : Com1011m
/// 파  일  명 : Com1011m.aspx.cs
/// 설      명 : 프로그램관리
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2008-07-28 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Collections;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using SMFramework.Data;
using SMFramework.Utility;
using SMFramework.Web.UI.WebControls.Page;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;
using Updms.Com.Exe;

namespace Updms.Com
{
	public partial class Com1011m : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Com1011m";
		public static readonly string gs_path_info = "/updms/Com/" + PID + ".aspx";

		Global global = new Global();

		//페이징
		private int li_cur_page, li_row_count, li_st_page, li_ed_page;
		protected int li_page_size = GRID_PAGESIZE;// 한 페이지에 출력될 행의수

		//검색
		protected string kw1 = "";	// 아이디
		protected string kw2 = "";	// 시스템
		protected string kw3 = "";	// 접근권한

		//메뉴 선택값
		protected string gs_sm = "";

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SearchProcess();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetClientScript();
			SetPgmClass();
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion

		#region SetClientScript

		private void SetClientScript()
		{
			//onKeyPress이벤트 (엔터검색)
			txt_search_pgm_nm.Attributes.Add("onkeypress", "enterSearch(event)");
		}

		#endregion

		#region SetInit, SetSearchParameter, ShowKeywordLabel

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";
			if (Request.QueryString["page"] == null || int.Parse(Request.QueryString["page"]) == 1)
			{
				li_cur_page = 1;
				li_st_page = 0;
				li_ed_page = li_page_size;
			}
			else
			{
				li_cur_page = int.Parse(Request.QueryString["page"]);
				li_st_page = (int.Parse(Request.QueryString["page"]) - 1) * li_page_size;
				li_ed_page = li_st_page + li_page_size;
			}

			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
					{
						kw1 = ddl_search_pgm_class.SelectedValue;
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
						ddl_search_pgm_class.SelectedValue = kw1;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw2"]))	// url에 값이 없으면
					{
						kw2 = txt_search_pgm_nm.Text.Trim();
					}
					else
					{
						kw2 = Server.UrlDecode(Request.QueryString["kw2"]);
						txt_search_pgm_nm.Text = kw2;
					}

					if (String.IsNullOrEmpty(Request.QueryString["kw3"]))	// url에 값이 없으면
					{
						kw3 = ddl_search_access_level.SelectedValue;
					}
					else
					{
						kw3 = Server.UrlDecode(Request.QueryString["kw3"]);
						ddl_search_access_level.SelectedValue = kw3;
					}
					break;
				case "SEARCH":
					kw1 = ddl_search_pgm_class.SelectedValue;
					kw2 = txt_search_pgm_nm.Text.Trim();
					kw3 = ddl_search_access_level.SelectedValue;
					break;
			}
		}

		//검색키워드
		private void ShowKeywordLabel()
		{
			string ls_kw1 = ConversionUtil.CompareReplace(ddl_search_pgm_class.SelectedItem.Text, DDL_SELECT, "-");
			lbl_search_keyword.Text = ls_kw1 + " / " + kw2 + " / " + kw3;
		}

		#endregion

		#region 마스터 Method (SetPgmClass)

		//시스템 바인딩
		private void SetPgmClass()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			Com1011m_NT _Com1011m_NT = new Com1011m_NT();

			lo_dp.AddProperty("ls_lang_set", typeof(string), LANG_SET);

			lo_ds.Merge(_Com1011m_NT.GetSystemList(lo_dp));

			// 검색
			ddl_search_pgm_class.Items.Clear();
			ddl_search_pgm_class.DataSource = lo_ds;
			ddl_search_pgm_class.DataMember = "UPDMS_COM_PGM";
			ddl_search_pgm_class.DataTextField = "Text";
			ddl_search_pgm_class.DataValueField = "Class";
			ddl_search_pgm_class.DataBind();
			ddl_search_pgm_class.Items.Insert(0, new ListItem(DDL_SELECT, ""));
		}

		#endregion

		#region 디렉토리 변경 - 메뉴정렬관리(Com1020m)로 기능대체함. 2012-09-12

		////디렉토리를 변경하면
		//protected void ddl_dir_depth_SelectedIndexChanged(object sender, EventArgs e)
		//{
		//    //라벨선택은 무효
		//    if (ddl_dir_depth.SelectedIndex != 0)
		//    {
		//        for (int i = 0; i < GridView1.Rows.Count; i++)
		//        {
		//            GridViewRow row = GridView1.Rows[i];
		//            HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check");

		//            if (cb.Checked)
		//            {
		//                string ls_seq = GridView1.DataKeys[i].Values["Seq"].ToString();
		//                MoveProcess(ls_seq, ddl_dir_depth.SelectedValue);
		//            }
		//        }
		//    }
			
		//    //실행후 숨김
		//    SearchProcess();
		//}	
		
		#endregion

		#region CRUD (SelectProcess, InsertProcess, UpdateProcess, DeleteProcess, MoveProcess, SearchProcess)

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();
			int li_page_count;

			//검색
			lo_dp.AddProperty("ls_pgm_class", typeof(string), kw1);
			lo_dp.AddProperty("ls_pgm_nm", typeof(string), kw2);
			lo_dp.AddProperty("ls_access_level", typeof(string), kw3);

			using (Com1011m_NT _Com1011m_NT = new Com1011m_NT())
			{
				li_row_count = _Com1011m_NT.GetSearchCount(lo_dp);	// 검색된 행수
				li_page_count = (int)((li_row_count - 1) / li_page_size) + 1;	// 총페이지수 계산

				//모두보기/페이징
				lo_dp.AddProperty("li_st_page", typeof(Int32), (cb_list_all.Checked) ? 0 : li_st_page);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), (cb_list_all.Checked) ? li_row_count : li_ed_page);
				lbl_page.Visible = !cb_list_all.Checked;

				lo_ds.Merge(_Com1011m_NT.SelectProcess(lo_dp));

				GridView1.DataSource = lo_ds;
				GridView1.DataBind();

				Pager pager = new Pager(this, ref lbl_page);
				pager.PageNavigation(
					li_cur_page,
					li_page_count,
					gs_path_info + "?sm=" + gs_sm + "&kw1=" + Server.UrlEncode(kw1) + "&kw2=" + Server.UrlEncode(kw2) + "&kw3=" + Server.UrlEncode(kw3) + "&page=");

				//결과출력(키워드, 검색행수)
				ShowKeywordLabel();
				lbl_result_count.Text = li_row_count.ToString("#,###,##0");
			}
		}

		//저장
		private void InsertProcess()
		{
			using (Com1011m_RT _Com1011m_RT = new Com1011m_RT())
			{
				int li_return = _Com1011m_RT.InsertProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_007" : "MSG_ERR_105";	//저장되었습니다:저장할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//수정
		private void UpdateProcess()
		{
			using (Com1011m_RT _Com1011m_RT = new Com1011m_RT())
			{
				int li_return = _Com1011m_RT.UpdateProcess(SetValue());
				string ls_msg_id = (li_return > 0) ? "MSG_INF_006" : "MSG_ERR_104";	//수정되었습니다:수정할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		//삭제
		private void DeleteProcess(string ls_xml)
		{
			using (Com1011m_RT _Com1011m_RT = new Com1011m_RT())
			{
				int li_return = _Com1011m_RT.DeleteProcess(ls_xml);
				string ls_msg_id = (li_return > 0) ? "MSG_INF_004" : "MSG_ERR_103";	//삭제되었습니다:삭제할 수 없습니다
				CallMsgBoxInAjax(ls_msg_id);

				SearchProcess();
			}
		}

		////이동
		//private void MoveProcess(string ls_seq, string ls_dir_depth)
		//{
		//    DataPack lo_dp = new DataPack();
		//    lo_dp.AddProperty("Seq", typeof(string), ls_seq);
		//    lo_dp.AddProperty("Dir_depth", typeof(string), ls_dir_depth);
		//    lo_dp.AddProperty("Update_User", typeof(string), USER_ID);

		//    using (Com1011m_RT _Com1011m_RT = new Com1011m_RT())
		//    {
		//        int li_return = _Com1011m_RT.SetDirDepthBySeq(lo_dp);
		//        string ls_msg_id = (li_return > 0) ? "MSG_INF_013" : "MSG_ERR_132";	//이동되었습니다:이동할 수 없습니다
		//        CallMsgBoxInAjax(ls_msg_id);
		//    }
		//}

		//검색
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();
			ClearValue();
			SelectProcess();
		}

		#endregion

		#region SetValue, ClearValue

		//SetValue
		private DataPack SetValue()
		{
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("Seq", typeof(string),			lbl_pk.Text);
			lo_dp.AddProperty("Pgm_Id", typeof(string), 		txt_pgm_id.Text);
			lo_dp.AddProperty("Pgm_Class", typeof(string), 		txt_pgm_class.Text);
			lo_dp.AddProperty("Pgm_Nm", typeof(string), 		txt_pgm_nm.Text);
			lo_dp.AddProperty("Pgm_Nm_Eng", typeof(string),		ConversionUtil.DefaultValue(txt_pgm_nm_eng.Text));
			lo_dp.AddProperty("Pgm_Url", typeof(string), 		ConversionUtil.DefaultValue(txt_pgm_url.Text));
			lo_dp.AddProperty("Pgm_Div", typeof(string), 		ddl_pgm_div.SelectedValue);
			lo_dp.AddProperty("Dir_Depth", typeof(string), 		ConversionUtil.DefaultValue(txt_dir_depth.Text, "DAZ9999"));
			lo_dp.AddProperty("Access_Level", typeof(string),	ConversionUtil.DefaultValue(txt_access_level.Text.Trim(), "9"));
			lo_dp.AddProperty("Use_Yn", typeof(string), 		rbl_use_yn.SelectedValue);
			lo_dp.AddProperty("Exp_Yn", typeof(string), 		rbl_exp_yn.SelectedValue);
			lo_dp.AddProperty("Create_User", typeof(string), 	USER_ID);
			lo_dp.AddProperty("Create_Dt", typeof(string),		"");
			lo_dp.AddProperty("Update_User", typeof(string), 	USER_ID);
			lo_dp.AddProperty("Update_Dt", typeof(string), 		"");

			return lo_dp;
		}

		//ClearValue
		private void ClearValue()
		{
			lbl_pk.Text = "";
			h_no.Value = "";
			txt_pgm_id.Text = "";
			txt_pgm_class.Text = "";
			txt_pgm_nm.Text = "";
			txt_pgm_nm_eng.Text = "";
			txt_pgm_url.Text = "";
			txt_dir_depth.Text = "";
			rbl_use_yn.SelectedIndex = 0;
			rbl_exp_yn.SelectedIndex = 1;
		}

		#endregion

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
		}

		// ChangePageMode
		private void ChangePageMode()
		{
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion

		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onmouseover", "overBackground('GridView1', " + (e.Row.RowIndex + 1) + ")");
				e.Row.Attributes.Add("onmouseout", "outBackground('GridView1', 1)");

				//번호
				e.Row.Cells[1].Text	= cb_list_all.Checked
					? (li_row_count - e.Row.RowIndex).ToString() 
					: ((li_row_count - ((li_cur_page - 1) * li_page_size)) - e.Row.RowIndex).ToString();
					
				for (int i = 0; i < GridView1.Columns.Count; i++)
				{
					// 프로그램별 구분선
					if (e.Row.Cells[7].Text == "#")
					{
						e.Row.Attributes.Add("class", "b");
						string class_nm = "div_line_t_sld";

						//사용여부(11),대표여부(12) 색깔구분
						if (i == 11 || i == 12)
						{
							e.Row.Cells[i].Attributes.Add("class", (e.Row.Cells[i].Text == "Y") ? class_nm + " color_darkred" : class_nm + " color_gray");
						}
						else
						{
							e.Row.Cells[i].Attributes.Add("class", class_nm);
						}
					}
					else
					{
						if (i == 11 || i == 12)
						{
							e.Row.Cells[i].Attributes.Add("class", (e.Row.Cells[i].Text == "Y") ? "color_darkred" : "color_gray");
						}
					}
				}
			}			
		}

		//RowCommand
		protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
		{
			GridView gv = (GridView)sender;
			GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);

			LinkButton lbtn_rc = (LinkButton)GridView1.Rows[row.RowIndex].FindControl("lbtn_rc");

			//row.Cells[0].Text.ToString();//0.체크박스
			h_no.Value						= row.Cells[1].Text.ToString();							//1.번호
			lbl_pk.Text						= gv.DataKeys[row.RowIndex].Values["Seq"].ToString();	//2.Seq
			txt_pgm_id.Text					= lbtn_rc.Text;											//3.Pgm_Id (template)
			txt_pgm_class.Text				= row.Cells[4].Text.Trim();								//4.Pgm_Class
			txt_pgm_nm.Text					= row.Cells[5].Text.Trim();								//5.Pgm_Nm
			txt_pgm_nm_eng.Text				= row.Cells[6].Text.Trim();								//6.Pgm_Nm_Eng
			txt_pgm_url.Text				= row.Cells[7].Text.Trim();								//7.Pgm_Url
			ddl_pgm_div.SelectedValue		= row.Cells[8].Text.Trim();								//8.Pgm_Div
			txt_dir_depth.Text				= row.Cells[9].Text.Trim();								//9.Dir_Depth
																									//10.Access_Level
			rbl_use_yn.SelectedValue		= row.Cells[11].Text.Trim();							//11.Use_Yn
			rbl_exp_yn.SelectedValue		= row.Cells[12].Text.Trim();							//12.Exp_Yn

			//만족도 슬라이더값
			CallJavaScriptMethodInAjax("setTimeout(\"setSliderValue(" + row.Cells[10].Text.ToString() + ",'AccessLevelSlider')\", 5);"); //10.Access_Level
		}

		#endregion

		#region 버튼이벤트

		//검색
		protected void ibtn_search_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}

		//저장
		protected void ibtn_save_Click(object sender, EventArgs e)
		{
			if (global.CheckSaveMode("UPDMS_COM_PGM", "Seq", lbl_pk.Text.Trim()))
			{
				UpdateProcess();
			}
			else
			{
				InsertProcess();
			}
		}

		//삭제
		protected void ibtn_delete_Click(object sender, EventArgs e)
		{
			StringBuilder sb = new StringBuilder();

			sb.Append("<UPDMS>");
			for (int i = 0; i < GridView1.Rows.Count; i++)
			{
				GridViewRow row = GridView1.Rows[i];
				HtmlInputCheckBox cb = (HtmlInputCheckBox)row.FindControl("cb_check");

				if (cb.Checked)
				{
					string ls_seq = GridView1.DataKeys[i].Values["Seq"].ToString();
					sb.Append("<UPDMS_COM_PGM>");
					sb.Append("<Seq>" + ls_seq + "</Seq>");
					sb.Append("</UPDMS_COM_PGM>");
				}
			}
			sb.Append("</UPDMS>");

			DeleteProcess(sb.ToString());
		}

		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			SetSearchParameter();

			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_pgm_class", typeof(string), kw1);
			lo_dp.AddProperty("ls_pgm_nm", typeof(string), kw2);
			lo_dp.AddProperty("ls_access_level", typeof(string), kw3);

			using (Com1011m_NT _Com1011m_NT = new Com1011m_NT())
			{
				li_row_count = _Com1011m_NT.GetSearchCount(lo_dp);

				lo_dp.AddProperty("li_st_page", typeof(Int32), 0);
				lo_dp.AddProperty("li_ed_page", typeof(Int32), li_row_count);

				lo_ds.Merge(_Com1011m_NT.SelectProcess(lo_dp));
			}
			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds, SetExcelHeaderX(global.GetColumnListByPgmId(PID, LANG_SET)));
		}

		//모두보기
		protected void cb_list_all_CheckedChanged(object sender, EventArgs e)
		{
			SearchProcess();
		}

		#endregion
	}
}
